package cn.dakaqi.controller.user;

import cn.dakaqi.entities.Group;
import cn.dakaqi.entities.GroupVolunteer;
import cn.dakaqi.entities.PinganOpen;
import cn.dakaqi.entities.user.User;
import cn.dakaqi.entities.user.UserOpenId;
import cn.dakaqi.entities.user.UserSupplement;
import cn.dakaqi.entities.user.Volunteer;
import cn.dakaqi.services.GroupService;
import cn.dakaqi.services.GroupVolunteerService;
import cn.dakaqi.services.PinganOpenService;
import cn.dakaqi.services.user.UserOpenService;
import cn.dakaqi.services.user.UserService;
import cn.dakaqi.services.user.UserSupplementService;
import cn.dakaqi.services.user.VolunteerService;
import cn.dakaqi.util.ConfigUtil;
import cn.dakaqi.utils.Clock;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.UUIDHexGenerator;
import cn.dakaqi.vo.request.pu.UserJoinRequestVo;
import cn.dakaqi.vo.response.BaseResponseVo;
import cn.dakaqi.vo.response.DataResponseVo;
import cn.dakaqi.vo.response.pu.UserInfoResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;

/**
 * @author beliveli on 2016/4/7.
 *         用户
 */
@RestController
@RequestMapping(value = "/api/v1/user")
@Slf4j
public class UserController {

    @Resource
    private UserSupplementService userSupplementService;

    @Resource
    private UserOpenService userOpenService;

    @Resource
    private UserService userService;

    @Resource
    private VolunteerService volunteerService;

    @Resource
    private GroupService groupService;

    @Resource
    private GroupVolunteerService groupVolunteerService;

    @Resource
    private PinganOpenService pinganOpenService;

    private static int PU_OTHER_USER_TYPE = 11;

    @ResponseBody
    @RequestMapping(value = "/findByUserId", method = RequestMethod.POST, consumes = "application/json")
    public DataResponseVo<UserSupplement> findByUserId() {
        return new DataResponseVo<>(0, "", userSupplementService.findByUserId(155));
    }

    @ResponseBody
    @RequestMapping(value = "/findByOtherUserId", method = RequestMethod.POST, consumes = "application/json")
    public DataResponseVo<UserInfoResponseVo> findByOtherUserId(@RequestBody UserJoinRequestVo userJoinRequestVo) {
        UserOpenId userOpenId = userOpenService.findByOpenId(userJoinRequestVo.getOtherUserId() + "", PU_OTHER_USER_TYPE);

        if(userOpenId == null){
            return new DataResponseVo<>(0,"",null);
        }

        UserInfoResponseVo responseVo;

        Volunteer volunteer = volunteerService.findByMemberCode(userOpenId.getMemberCode());
        User user = userService.findOne(volunteer.getUserId());

        responseVo = UserInfoResponseVo.build(user, volunteer);

        PinganOpen pinganOpen = pinganOpenService.findByVolunteerCodeAndStatus(volunteer.getMemberCode(), 1);
        if(pinganOpen != null){
            responseVo.setIsInsure(1);
        }

        return new DataResponseVo<>(0, "", responseVo);
    }

    @ResponseBody
    @RequestMapping(value = "/userJoin", method = RequestMethod.POST, consumes = "application/json")
    public DataResponseVo<UserInfoResponseVo> userJoin(@RequestBody UserJoinRequestVo userJoinRequestVo) {
        UserInfoResponseVo responseVo;
        Volunteer volunteer;
        UserOpenId userOpenId = userOpenService.findByOpenId(userJoinRequestVo.getOtherUserId() + "", PU_OTHER_USER_TYPE);

        if (userOpenId == null) {
            //创建用户
            User user = createUser(userJoinRequestVo);
            //创建用户
            volunteer = createVolunteer(user, userJoinRequestVo.getIdCard());

            //创建第三方账户关联
            userOpenId = UserOpenId.build(volunteer.getMemberCode(), 11, userJoinRequestVo.getOtherUserId() + "",
                    new Timestamp(new Date().getTime()), null, null);
            userOpenService.save(userOpenId);

            StringBuilder groupName = new StringBuilder().append(userJoinRequestVo.getSchool()).append("-").
                    append(userJoinRequestVo.getFaculty()).append("-").append(userJoinRequestVo.getClasses());

            Group group = groupService.findByGroupName(groupName.toString());

            if (group == null) {
                createGroup(userJoinRequestVo, volunteer, groupName);
            } else {
                //加入组织
                GroupVolunteer groupVolunteer = joinGroup(group, volunteer);//join group
                //审核通过
                groupVolunteerService.updateStatus(groupVolunteer.getId(), DKQConstant.APPLY_STATUS_OK, group.getCreateUser().getMemberCode(), "");
            }

            responseVo = UserInfoResponseVo.build(user, volunteer);
        } else {
            volunteer = volunteerService.findByMemberCode(userOpenId.getMemberCode());
            User user = userService.findOne(volunteer.getUserId());

            responseVo = UserInfoResponseVo.build(user, volunteer);
        }

        PinganOpen pinganOpen = pinganOpenService.findByVolunteerCodeAndStatus(volunteer.getMemberCode(), 1);
        if(pinganOpen != null){
            responseVo.setIsInsure(1);
        }

        return new DataResponseVo<>(0, "", responseVo);
    }

    /**
     * 创建组织
     *
     * @param userJoinRequestVo 用户输入参数
     * @param volunteer         志愿者信息
     * @param groupName         组织名称
     */
    private void createGroup(UserJoinRequestVo userJoinRequestVo, Volunteer volunteer, StringBuilder groupName) {
        Group group;
        group = new Group();
        group.setName(groupName.toString());
        group.setMonitor(volunteer.getRealName());
        group.setPhone(volunteer.getMobile());
        group.setCreateUser(volunteer);
        group.setProvince(userJoinRequestVo.getProvince());
        group.setCity(userJoinRequestVo.getCity());
        group.setDistrict(userJoinRequestVo.getDistrict());
        groupService.save(group);
    }

    /**
     * 创建志愿者
     *
     * @param user   用户对象
     * @param IDCard 用户身份证
     * @return 志愿者对象
     */
    private Volunteer createVolunteer(User user, String IDCard) {
        Volunteer volunteer = new Volunteer();
        volunteer.setMemberCode(UUIDHexGenerator.generator());
        volunteer.setCrateTime(Clock.DEFAULT.getCurrentDate());
        volunteer.setMobile(user.getMobile());
        volunteer.setNickName(user.getNickName());
        volunteer.setRealName(user.getRealName());
        volunteer.setUserId(user.getId());
        volunteer.setTimes(0L);
        volunteer.setHeadUrl(DKQConstant.HEAR_URL);
        volunteer.setSex("男");
        volunteer.setClient(user.getClient());
        volunteer.setActs(0);
        volunteer.setRank(0);
        volunteer.setCardNO(IDCard);
        volunteer.setCardType("CID");
        volunteer.setBirthDay(IDCard.substring(6, 10) + "-" + IDCard.substring(10, 12) + "-" + IDCard.substring(12, 14));
        return volunteerService.saveVolunteer(volunteer);
    }

    /**
     * 创建用户
     *
     * @param userJoinRequestVo 输入参数
     * @return 用户对象
     */
    private User createUser(UserJoinRequestVo userJoinRequestVo) {
        User user = new User();
        user.setMobile(userJoinRequestVo.getPhone());
        user.setPassword(RandomStringUtils.random(8)); //默认密码随机字符串
        user.setRealName(userJoinRequestVo.getRealName());
        user.setNickName(userJoinRequestVo.getRealName());
        user.setRoles("user");
        user.setEmail(userJoinRequestVo.getPhone() + "@dakaqi.cn");
        user.setArea(userJoinRequestVo.getCity());
        user.setClient(ConfigUtil.getClientId());

        user = userService.saveUserOnly(user, "dakaqiCode");
        return user;
    }

    /**
     * 加入组织
     *
     * @param group     要加入的组织
     * @param volunteer 要加入的人
     * @return 组织志愿者关系对象
     */
    private GroupVolunteer joinGroup(Group group, Volunteer volunteer) {

        GroupVolunteer groupVolunteer = new GroupVolunteer();
        groupVolunteer.setVolunteer(volunteer);
        groupVolunteer.setGroup(group);
        groupVolunteer.setCreateTime(Clock.DEFAULT.getCurrentDate());
        groupVolunteer.setRole(DKQConstant.ROLES_VOLUNTEER);
        groupVolunteer.setStatus(DKQConstant.APPLY_STATUS);

        groupVolunteer = groupVolunteerService.save(groupVolunteer);
        return groupVolunteer;
    }
}








